﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using LuaC;
using Language;
using System.IO;
using System.Threading;
using Smdn.Windows.UserInterfaces.Shells;
using CRC32;
using System.Diagnostics;
using SevenZip;
using System.Drawing.Drawing2D;
using System.Reflection;
using LuaBoardPlugin;

namespace LuaBoard
{
    public partial class LuaBoard : Form
    {
        private List<IPlugin> ipi=new List<IPlugin>();

        public LanguageData lang = Language.CommLanguageData.data;
        private string LuaSystemPath = "";
        private string MainPath = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
        private List<Label> LableList = new List<Label>();
        private bool Ready = false;
        public MainHost LuaBoardHost;

        public string AppLocPath
        {
            get { return Common.AppLocPath; }
            set { Common.AppLocPath = value; }
        }

        public LuaBoard()
        {
            InitializeComponent();

            TabPage tp = new TabPage("test");
            this.toolTip.Popup += new System.Windows.Forms.PopupEventHandler(this.toolTip_Popup); 
            this.toolTip.Draw += new System.Windows.Forms.DrawToolTipEventHandler(this.toolTip_Draw);

            LuaSystemPath = Path.Combine(System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase, @"system\");

            Common.setup(LuaSystemPath);

            lang.LoadINI(LuaSystemPath);

            this.richTextBox_Log.SelectedText = "CodePage:" + lang.CP_Name + Environment.NewLine;
            this.toolStripStatusLabel_Stat.Text = lang.GetString("Ready");
            this.toolStripProgressBar.Visible = false;

            //Check AppLoc
            string WinAppLocPath = Path.Combine(Environment.GetEnvironmentVariable("SystemRoot"), "AppPatch");
            if (Directory.Exists(WinAppLocPath))
            {
                AppLocPath = Path.Combine(WinAppLocPath, "AppLoc.exe");
                if (File.Exists(AppLocPath))
                {
                    codePageToolStripMenuItem.Enabled = true;
                    Common.AppLocEnable = true;
                }
                else
                    AppLocPath = "";
            }

            //7zip
            SevenZipCompressor.SetLibraryPath(Path.Combine(System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase, @"7z.dll"));
            Archiver.C7Z.MainForm = this;

            comboBox_Option_CmpLevel.SelectedIndex = Common.CompressionLevel;
            checkBox_ShowDebug.Checked = Common.ShowDebugMsg;

            //Language setup
            if (Common.LuaBoardTitle != "")
                this.Text = string.Format("{0} - LuaBoard {1}", lang.GetString(Common.LuaBoardTitle), base.ProductVersion);
            else
                this.Text = string.Format("LuaBoard {0}", base.ProductVersion);
            textBox_Title.Text = lang.GetString(Common.LuaBoardTitle);
            label_Title.Text = lang.GetString(label_Title.Text);
            tabPageMain.Text = lang.GetString(tabPageMain.Text);
            tabPageOption.Text = lang.GetString(tabPageOption.Text);
            runToolStripMenuItem.Text = lang.GetString(runToolStripMenuItem.Text);
            newItemToolStripMenuItem.Text = lang.GetString(newItemToolStripMenuItem.Text);
            copyToolStripMenuItem.Text = lang.GetString(copyToolStripMenuItem.Text);
            clearToolStripMenuItem.Text = lang.GetString(clearToolStripMenuItem.Text);
            deleteToolStripMenuItem.Text = lang.GetString(deleteToolStripMenuItem.Text);
            argumentsToolStripMenuItem.Text = lang.GetString(argumentsToolStripMenuItem.Text);
            textBox_CheckFile.Text = lang.GetString(textBox_CheckFile.Text);
            newFolderToolStripMenuItem1.Text = lang.GetString(newFolderToolStripMenuItem1.Text);
            labelCompressionLevel.Text = lang.GetString(labelCompressionLevel.Text);
            exportTo7zipToolStripMenuItem.Text = lang.GetString(exportTo7zipToolStripMenuItem.Text);
            saveFileDialog1.Title = lang.GetString(exportTo7zipToolStripMenuItem.Text);
            for (int i = 0; i < 6; i++)
            {
                string name = lang.GetString(comboBox_Option_CmpLevel.Items[i].ToString());
                comboBox_Option_CmpLevel.Items[i] = name;
                
            }

            LoadPlugins();

            Ready = true;
        }

        private void LoadPlugins()
        {
            string path = Application.StartupPath;
            string[] pluginFiles = Directory.GetFiles(path, "*.dll");
            
            if (pluginFiles.Length == 0) return;

            LuaBoardHost = new MainHost();

            for (int i = 0; i < pluginFiles.Length; i++)
            {
                string args = Path.GetFileNameWithoutExtension(pluginFiles[i]);

                bool skip = false;
                switch (args.ToLower())
                {
                    case "7z":
                    case "lua51":
                    case "luainterface":
                    case "sevenzipsharp":
                    case "luaboardplugin":
                        skip = true;
                        break;
                }
                if (skip) continue;

                Type ObjType = null;
                //IPlugin ipi;
                // load the dll
                try
                {
                    
                    // load it
                    Assembly ass = null;
                    ass = Assembly.Load(args);
                    if (ass != null)
                    {
                        
                        ObjType = ass.GetType(args + ".PlugIn");
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, lang.GetString("Error"), MessageBoxButtons.OKCancel, MessageBoxIcon.Error);
                    continue;
                }
                try
                {
                    // OK Lets create the object as we have the Report Type
                    if (ObjType != null)
                    {
                        IPlugin ip = (IPlugin)Activator.CreateInstance(ObjType);
                        ip.Host = LuaBoardHost;
                        string msg = string.Format("Loaded plugin : {0}.dll", args);
                        lua_LuaMsgEvent(this, new LuaClassMsgEventArgs(msg, LuaClassEventType.log_debug));
                        ipi.Add(ip);
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, lang.GetString("Error"), MessageBoxButtons.OKCancel, MessageBoxIcon.Error);
                    continue;
                }

                //				Start(assemname);
            }

        }
        public void RegisterLua(LuaInterface.Lua lua)
        {
            if (ipi==null) return;
            for (int i = 0; i < ipi.Count; i++)
            {
                if (ipi[i] != null)
                {
                    try
                    {
                        ipi[i].RegisterLuaFunction(lua);
                    }
                    catch
                    {
                        string msg = string.Format("{0}:Register error.", ipi[i].Name);
                        lua_LuaMsgEvent(this, new LuaClassMsgEventArgs(msg, LuaClassEventType.log_error));
                    }

                }
            }
        }

        #region Constants

        private const int TOOLTIP_WIDTH = 200;
        private const int TOOLTIP_HEIGHT = 60;
        private const int BORDER_THICKNESS = 1;
        private const int PADDING = 6;
        private const int DEFAULT_IMAGE_WIDTH = 200;

        #endregion

        #region Fields

        private static Color myBorderColor = Color.DarkRed;
        private static Font myFont = new Font("Arial", 9);

        private StringFormat myTextFormat = new StringFormat();

        private Rectangle myImageRectangle = new Rectangle();
        private Rectangle myTextRectangle = new Rectangle();
        private Rectangle myToolTipRectangle = new Rectangle();

        private Brush myBackColorBrush = new SolidBrush(Color.AntiqueWhite);
        private Brush myTextBrush = new SolidBrush(Color.Black);
        private Brush myBorderBrush = new SolidBrush(myBorderColor);

        private Size mySize = new Size(TOOLTIP_WIDTH, TOOLTIP_HEIGHT);

        private int myInternalImageWidth = DEFAULT_IMAGE_WIDTH;
        private int myInternalImageHeight = DEFAULT_IMAGE_WIDTH;
        private bool myAutoSize = true;
        #endregion

        private void toolTip_Draw(object sender, DrawToolTipEventArgs e)
        {
            Image toolTipImage = null;

            ListViewItem lv = (ListViewItem)this.toolTip.Tag;
            LuaItem lp = (LuaItem)lv.Tag;
            string[] info = lp.GetInfo();
            if (info.Length > 1 && info[1] != null) toolTipImage = new Bitmap(info[1]);
            
            e.Graphics.CompositingQuality = CompositingQuality.HighQuality;


            myToolTipRectangle.Size = e.Bounds.Size;

            e.Graphics.FillRectangle(myBorderBrush, myToolTipRectangle);

            myImageRectangle = Rectangle.Inflate(myToolTipRectangle,  - BORDER_THICKNESS, -BORDER_THICKNESS);
            e.Graphics.FillRectangle(myBackColorBrush, myImageRectangle);
            if (toolTipImage != null)
            {
                myImageRectangle.Width = myInternalImageWidth; myImageRectangle.Height = myInternalImageHeight;
                if (myInternalImageHeight > myInternalImageWidth)
                {
                    myTextRectangle = new Rectangle(myImageRectangle.Right + BORDER_THICKNESS, myImageRectangle.Top + BORDER_THICKNESS,
                    (myToolTipRectangle.Width - myImageRectangle.Right - BORDER_THICKNESS), myImageRectangle.Height);
                    myTextRectangle.Location = new Point(myImageRectangle.Right, myImageRectangle.Top);

                    int y = (myToolTipRectangle.Height - myInternalImageHeight) / 2;
                    myImageRectangle.Y += y;
                }
                else
                {
                    myTextRectangle = new Rectangle(BORDER_THICKNESS, (myToolTipRectangle.Height - myImageRectangle.Bottom - BORDER_THICKNESS),
                    myToolTipRectangle.Width-3, myToolTipRectangle.Height - 3);
                    myTextRectangle.Location = new Point(myImageRectangle.Left, myImageRectangle.Bottom);

                    int x = (myToolTipRectangle.Width - myInternalImageWidth) / 2;
                    myImageRectangle.X += x;
                }
                
                e.Graphics.FillRectangle(myBackColorBrush, myTextRectangle);
                e.Graphics.DrawImage(toolTipImage, myImageRectangle);
                e.Graphics.DrawString(e.ToolTipText, myFont, myTextBrush, myTextRectangle, myTextFormat);
            }
            else
            {
                e.Graphics.DrawString(e.ToolTipText, myFont,
                myTextBrush, myImageRectangle, myTextFormat);
            }

        }

        private void toolTip_Popup(object sender, PopupEventArgs e)
        {
            Size oldSize = e.ToolTipSize;
            if (e.ToolTipSize.Height > 1024) oldSize.Height = (int)((float)DEFAULT_IMAGE_WIDTH);
            if (e.ToolTipSize.Width > 1024) oldSize.Width = (int)((float)DEFAULT_IMAGE_WIDTH);

            if (!this.toolTip.OwnerDraw) { e.ToolTipSize = oldSize; return; }

            if (!myAutoSize)
            {
                e.ToolTipSize = mySize;
                myInternalImageWidth = mySize.Height;
            }
            else
            {
                Image toolTipImage = null;

                ListViewItem lv = (ListViewItem)this.toolTip.Tag;
                LuaItem lp = (LuaItem)lv.Tag;
                string[] info = lp.GetInfo();
                if (info.Length > 1 && info[1] != null)
                {
                    if (File.Exists(info[1]))
                        toolTipImage = new Bitmap(info[1]);
                }

                if (toolTipImage != null)
                {
                    float  w = toolTipImage.Width;
                    float h = toolTipImage.Height;
                    if (w > (float)DEFAULT_IMAGE_WIDTH)
                    {
                        w = (float)DEFAULT_IMAGE_WIDTH;
                        h = (w / (float)toolTipImage.Width) * (float)toolTipImage.Height;
                    }
                    if (h > (float)DEFAULT_IMAGE_WIDTH)
                    {
                        w = ((float)DEFAULT_IMAGE_WIDTH / h) * w;
                        h = (float)DEFAULT_IMAGE_WIDTH;
                        
                    }
                    myInternalImageWidth = (int)w;
                    myInternalImageHeight = (int)h;

                    if (h > w)
                    {
                        oldSize.Width += myInternalImageWidth + PADDING;
                        if (oldSize.Height < myInternalImageHeight)
                            oldSize.Height = myInternalImageHeight;
                    }
                    else
                    {
                        oldSize.Height += myInternalImageHeight + PADDING;
                        if (oldSize.Width < myInternalImageWidth)
                            oldSize.Width = myInternalImageWidth;
                    }

                }
                else
                {
                    oldSize.Width += PADDING;
                }
            }
            e.ToolTipSize = oldSize;

        }
        private void LuaBoard_Load(object sender, EventArgs e)
        {
            Properties.Settings settings = Properties.Settings.Default;

            int screenWidth = Screen.PrimaryScreen.Bounds.Width;
            int screenHeight = Screen.PrimaryScreen.Bounds.Height;
            if (settings.Location != new Point(0, 0) && settings.Location.X < screenWidth - 40 && settings.Location.Y < screenHeight - 40 && settings.Location.X > 0 && settings.Location.Y > 0)
            {
                this.Location = settings.Location;
                this.Size = settings.FormSize;
                splitContainer1.SplitterDistance = settings.SplitterDist;
                //StreamWriter sw = new StreamWriter("log.txt", false);
                //sw.Write(string.Format("windows location = {0},{1}\r\n", settings.Location.X, settings.Location.Y));
                //sw.Close();
                
            }

            
            LuaListView._MainTabs = tabControl1;
            LuaListView.setup(this, this.listView_Item, this.treeView);
            EnterList(LuaListView.rootnode);

            this.richTextBox_Log.Focus();
            this.richTextBox_Log.SelectionStart = this.richTextBox_Log.Text.Length;
            this.richTextBox_Log.ScrollToCaret();

            listView_Item.Sorting = SortOrder.Ascending;

            int Width = splitContainer1.Panel1.Width - 5;
            int Height = splitContainer1.Panel1.Height - 30;
            listView_Item.Size = new Size(Width, Height);

            Width = splitContainer1.Panel2.Width - 5;
            Height = splitContainer1.Panel2.Height -5;
            richTextBox_Log.Size = new Size(Width, Height);
            
        }
        private void LuaBoard_FormClosing(object sender, FormClosingEventArgs e)
        {
            Properties.Settings settings = Properties.Settings.Default;
            if (this.Location.X < 0 || this.Location.Y < 0) return;
            settings.Location = this.Location;
            settings.FormSize = this.Size;
            settings.SplitterDist = splitContainer1.SplitterDistance;
            settings.Save();
        }

        private delegate void InvokeNumber(int value);
        private delegate void InvokeBool(bool value);
        private delegate void InvokeString(string value);

        public void lua_LuaMsgEvent(object src, LuaClassMsgEventArgs e)
        {
            string msg = e.Message;
            
            if (src.GetType() ==typeof( LuaClass))
            {
                LuaClass lc = (LuaClass)src;
                msg = string.Format("[{0}]:{1}", lc.Name, msg);
            }
            else if (src.GetType() == typeof(LuaItem))
            {
                LuaItem li = (LuaItem)src;
                msg = string.Format("[{0}]:{1}", li.Name, msg);
            }
            if (e.EventType != LuaClassEventType.Status)
            {
                msg += Environment.NewLine;
            }

            this.richTextBox_Log.Focus();
            int si = 0;
            si = this.richTextBox_Log.Text.Length;
            this.richTextBox_Log.SelectionStart = si;
            switch (e.EventType)
            {
                case LuaClassEventType.log:
                    this.richTextBox_Log.SelectedText = msg;
                    break;
                case LuaClassEventType.log_error:
                    this.richTextBox_Log.SelectionColor = Color.Red;
                    this.richTextBox_Log.SelectedText = msg;
                    break;
                case LuaClassEventType.log_Warning:
                    this.richTextBox_Log.SelectionColor = Color.Yellow;
                    this.richTextBox_Log.SelectedText = msg;
                    break;
                case LuaClassEventType.Status:
                    this.toolStripStatusLabel_Stat.Text = msg; 
                    this.statusStrip1.Refresh();
                    break;
                case LuaClassEventType.log_debug:
                    if (Common.ShowDebugMsg)
                    {
                        this.richTextBox_Log.SelectionColor = Color.Pink;
                        this.richTextBox_Log.SelectedText = msg;
                    }
                    break;
            }
            this.richTextBox_Log.SelectionStart = this.richTextBox_Log.Text.Length;
            this.richTextBox_Log.ScrollToCaret();
            this.richTextBox_Log.SelectionColor = Color.White;
        }

        public void lua_LuaProgressBarEvent(object src, LuaClassProgressBarEventArgs e)
        {
            switch (e.cmd)
            {
                case LuaClassProgressBarCmd.value:
                    this.toolStripProgressBar.Value = e.Value;
                    break;
                case LuaClassProgressBarCmd.hide:
                    this.toolStripProgressBar.Visible = false;
                    break;
                case LuaClassProgressBarCmd.init_show:
                    this.toolStripProgressBar.Maximum = e.Max;
                    this.toolStripProgressBar.Minimum = e.Min;
                    this.toolStripProgressBar.Value = e.Min;
                    this.toolStripProgressBar.Visible = true;
                    break;

            }
        }
        public int ProgressBarMax
        {
            set 
            {
                if (this.statusStrip1.InvokeRequired)
                    this.Invoke(new InvokeNumber(this.SetProgressBarMax), new object[] { value });   
                else
                    this.toolStripProgressBar.Maximum = value; 
            }
        }
        private void SetProgressBarMax(int max)
        {
            this.toolStripProgressBar.Maximum = max; 
        }
        public int ProgressBarMin
        {
            set 
            {
                if (this.statusStrip1.InvokeRequired)
                    this.Invoke(new InvokeNumber(this.SetProgressBarMin), new object[] { value });
                else
                    this.toolStripProgressBar.Minimum = value; 
            }
        }
        public void SetProgressBarMin(int min)
        {
            this.toolStripProgressBar.Minimum = min;
        }

        
        public int ProgressBarValue
        {
            get { return this.toolStripProgressBar.Value; }
            set 
            {
                if (this.statusStrip1.InvokeRequired)
                    this.Invoke(new InvokeNumber(this.SetProgressBarValue), new object[] { value });
                else
                {
                    this.toolStripProgressBar.Value = value;
                    this.statusStrip1.Refresh();
                }
            }
        }
        public void SetProgressBarValue(int value)
        {
            if (this.statusStrip1.InvokeRequired)
            {
                    this.Invoke(new InvokeNumber(this.SetProgressBarValue), new object[] { value });
            }
            else
            {
                this.toolStripProgressBar.Value = value;
                this.statusStrip1.Refresh();
            }
        }

        public bool ProgressBarVisible
        {
            set 
            {
                if (this.statusStrip1.InvokeRequired)
                    this.Invoke(new InvokeBool(this.SetProgressBarVisible), new object[] { value });
                else
                {
                    this.toolStripProgressBar.Visible = value;
                    this.statusStrip1.Refresh();
                }
            }
        }
        public void SetProgressBarVisible(bool value)
        {
            this.toolStripProgressBar.Visible = value;
            this.statusStrip1.Refresh();
        }

        public string StatusText
        {
            get 
            { 
                    return this.toolStripStatusLabel_Stat.Text; 
            }
            set 
            {
                if (this.statusStrip1.InvokeRequired)
                    this.Invoke(new InvokeString(this.SetStatusText), new object[] { value });
                else
                {
                    this.toolStripStatusLabel_Stat.Text = value;
                    this.statusStrip1.Refresh();
                }
            }
        }
        public void SetStatusText(string value)
        {
            this.toolStripStatusLabel_Stat.Text = value;
            this.statusStrip1.Refresh();
        }

        private void contextMenuStrip_Item_Opening(object sender, CancelEventArgs e)
        {
            foreach (object o in contextMenuStrip_Item.Items)
            {
                if (o is ToolStripMenuItem)
                {
                    ToolStripMenuItem tsmi = (ToolStripMenuItem)o;
                    if (tsmi.Tag is LuaItem_menu) tsmi.Visible = false;
                }
            }
            if (this.listView_Item.SelectedItems.Count == 0 ) //no select
            {
                this.runToolStripMenuItem.Visible = false;
                this.luaToolStripMenuItem.Visible = false;
                this.toolStripSeparator1.Visible = false;
                this.newItemToolStripMenuItem.Visible = true;
                this.deleteToolStripMenuItem.Visible = false;
                this.toolStripSeparator2.Visible = false;
                this.codePageToolStripMenuItem.Visible = false;
                this.toolStripSeparator3.Visible = false;
                this.argumentsToolStripMenuItem.Visible = false;
                this.toolStripSeparator4.Visible = false;

                this.toolStripSeparator6.Visible = false;
                this.exportTo7zipToolStripMenuItem.Visible = false;
            }
            else if (this.listView_Item.SelectedItems.Count > 0)
            {
                LuaItem lp = (LuaItem)this.listView_Item.FocusedItem.Tag;
                lp.Reload_ContextMenu();

                if (lp.Name == "..")
                {
                    this.runToolStripMenuItem.Visible = false;
                    this.luaToolStripMenuItem.Visible = false;
                    this.toolStripSeparator1.Visible = false;
                    this.newItemToolStripMenuItem.Visible = true;
                    this.deleteToolStripMenuItem.Visible = false;
                    this.toolStripSeparator2.Visible = false;
                    this.codePageToolStripMenuItem.Visible = false;
                    this.toolStripSeparator3.Visible = false;
                    this.argumentsToolStripMenuItem.Visible = false;
                    this.toolStripSeparator4.Visible = false;

                    this.toolStripSeparator6.Visible = false;
                    this.exportTo7zipToolStripMenuItem.Visible = false;
                    return;
                }

                this.runToolStripMenuItem.Visible = true;
                this.luaToolStripMenuItem.Visible = true;
                this.toolStripSeparator1.Visible = true;
                this.newItemToolStripMenuItem.Visible = false;
                this.deleteToolStripMenuItem.Visible = true;


                if (lp.IsFolder == true) //is folder
                {
                    this.luaToolStripMenuItem.Visible = false;
                    this.toolStripSeparator2.Visible = false;
                    this.codePageToolStripMenuItem.Visible = false;
                    this.argumentsToolStripMenuItem.Visible = false;
                    this.toolStripSeparator3.Visible = false;
                }
                else
                {

                    this.codePageToolStripMenuItem.Visible = true;
                    if (lp.CanRun && !lp.NoArguments)
                    {
                        this.toolStripSeparator3.Visible = true;
                        this.argumentsToolStripMenuItem.Visible = true;
                    }
                    else
                    {
                        this.toolStripSeparator3.Visible = false;
                        this.argumentsToolStripMenuItem.Visible = false;
                    }
                    lp.AddContextMenu(contextMenuStrip_Item);
                    this.toolStripTextBox_Arg.Text = lp.Arguments;
                    AppLocMenu(lp);
                    LuaContextMenu(lp);
                }
                if (lp.HaveContextMenu)
                    this.toolStripSeparator4.Visible = true;
                else
                    this.toolStripSeparator4.Visible = false;

                this.toolStripSeparator6.Visible = true;
                this.exportTo7zipToolStripMenuItem.Visible = true;
            }
        }
        private void LuaContextMenu(LuaItem lp)
        {
            this.luaToolStripMenuItem.DropDownItems.Clear();
            foreach(ToolStripItem lfp in lp.LuaFilePath)
            {
                this.luaToolStripMenuItem.DropDownItems.Add(lfp);
            }
        }
        private void listView_Item_ItemActivate(object sender, EventArgs e)
        {
            if (this.listView_Item.SelectedItems.Count == 0) return;
            LuaItem lp = (LuaItem)this.listView_Item.FocusedItem.Tag;
            if (lp.IsFolder == true) //group
            {
                EnterList(lp.tn);
            }
            else if (lp.UpTreeNode != null)
            {
                EnterList(lp.UpTreeNode);
            }
            else
            {
                RunLua(lp);
            }
            
        }

        private void RunLua(LuaItem lp)
        {
            if (lp.CanRun) lp.RunLua();
        }

        private void LuaBoard_Activated(object sender, EventArgs e)
        {
            
        }

        private void treeView_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            EnterList(e.Node);
        }
        private void InitDirLabel(string FullPath)
        {
            foreach (Label l in LableList)
            {
                splitContainer1.Panel1.Controls.Remove(l);
                l.Dispose();
            }
            LableList.Clear();

            List<string> list = Common.PathList(FullPath);
            int count = 0;
            string path = "";
            foreach (string l in list)
            {
                path += l;
                Label lb = new Label();
                lb.AutoSize = true;
                if (count + 1 < list.Count)
                {
                    lb.Font = new System.Drawing.Font(lb.Font.Name, 9F, System.Drawing.FontStyle.Underline, System.Drawing.GraphicsUnit.Point, ((byte)(136)));
                    lb.Cursor = Cursors.Hand;
                    lb.Click += new System.EventHandler(this.LabelPath_Click);
                    lb.MouseMove += new MouseEventHandler(this.LabelPath_MouseMove);
                }
                lb.ForeColor = Color.BlueViolet;
                lb.Text = l;
                lb.Name = "LabelPath" + count;
                
                lb.Tag = LuaListView.GetTreeNode(path);
                LableList.Add(lb);
                splitContainer1.Panel1.Controls.Add(lb);

                count++;
                if (count < list.Count)
                {
                    lb = new Label();
                    lb.AutoSize = true;
                    lb.Text = ">";
                    lb.Name = "LabelPath" + count + "_";
                    LableList.Add(lb);
                    splitContainer1.Panel1.Controls.Add(lb);
                    path += "/";
                }
            }

            ReflashDirLabel();
        }
        private void ReflashDirLabel()
        {
            int x = 3;
            int resizelevel = 0;
            int MaxWidth = splitContainer1.Panel1.Width;
            foreach (Label lb in LableList)
            {
                lb.Location = new System.Drawing.Point(x, 3);
                lb.Size = new Size(lb.PreferredWidth, lb.PreferredHeight);
                x += lb.Size.Width;
            }

            while (x > MaxWidth)
            {
                resizelevel++; if (resizelevel >= LableList.Count) break;
                int fixcount=0;
                for (int i = 0; i < LableList.Count - 1; i++)
                {
                    if (LableList[i].Tag != null)
                    {
                        LableList[i].Text = "/"; fixcount++;
                        if (fixcount >= resizelevel) break;
                    }
                }
                x = 3;
                foreach (Label lb in LableList)
                {
                    lb.Location = new System.Drawing.Point(x, 3);
                    lb.Size = new Size(lb.PreferredWidth, lb.PreferredHeight);
                    x += lb.Size.Width;
                }
                
            }
            resizelevel = 0;
            while (x > MaxWidth)
            {
                resizelevel++; if (resizelevel >= LableList.Count) break;
                int fixcount = 0;
                for (int i = 1; i < LableList.Count - 3; i++)
                {
                    splitContainer1.Panel1.Controls.Remove(LableList[i]);
                    LableList[i].Dispose();
                    fixcount++;
                    LableList.Remove(LableList[i]); i--;
                    if (fixcount >= resizelevel) break;
                }
                x = 3;
                foreach (Label lb in LableList)
                {
                    if (lb != null)
                    {
                        lb.Location = new System.Drawing.Point(x, 3);
                        lb.Size = new Size(lb.PreferredWidth, lb.PreferredHeight);
                        x += lb.Size.Width;
                    }
                }

            }

        }
        private void LabelPath_Click(object sender, EventArgs e)
        {
            Label lb = (Label)sender;
            TreeNode tn = (TreeNode)lb.Tag;
            EnterList(tn);
        }
        private void LabelPath_MouseMove(object sender, MouseEventArgs e)
        {
            Label lb = (Label)sender;
            if (toolTip.Tag == (object)lb) return;
            TreeNode tn = (TreeNode)lb.Tag;
            string text = tn.Text;
            toolTip.OwnerDraw = false;
            toolTip.Tag = lb;
            toolTip.ToolTipTitle = text;
            toolTip.SetToolTip(lb, tn.FullPath);

            

        }

        private void EnterList(TreeNode tn)
        {
            TreeNode newSelected = tn;
            listView_Item.Items.Clear();
            LuaItem nodeLuaDir = (LuaItem)newSelected.Tag;
            ListViewItem item = null;

            if (nodeLuaDir.sublp != null)
            {
                foreach (LuaItem l in nodeLuaDir.sublp)
                {
                    if (l.sublp != null)
                    {
                        foreach (LuaItem ll in l.sublp) ll.Close();
                    }
                    l.Close();
                }
                nodeLuaDir.sublp.Clear();
            }
            
            newSelected.Nodes.Clear();

            LuaListView.LoadRootLoopDir(nodeLuaDir.dir, tn, nodeLuaDir, 0);

            //Background
            FileInfo[] fis = nodeLuaDir.dir.GetFiles("Background.*");
            bool bc = false;
            foreach (FileInfo fi in fis)
            {
                string ext = fi.Extension.ToLower();
                if (ext == ".jpg" || ext == ".jpeg" || ext == ".png" || ext == ".bmp" || ext == ".gif")
                {
                    listView_Item.BackgroundImage = Image.FromFile(fi.FullName);
                    listView_Item.BackgroundImageTiled = true;
                    bc = true;
                    break;
                }
            }
            if (!bc)
            {
                listView_Item.BackgroundImage = null;
            }

            if (nodeLuaDir.sublp != null)
            {
                ProgressBarMax = nodeLuaDir.sublp.Count;
                ProgressBarMin = 0;
                ProgressBarValue = 0;
                ProgressBarVisible = true;
                string txt = lang.GetString("Please wait...");
                StatusText = txt;
                foreach (LuaItem luaitem in nodeLuaDir.sublp)
                {
                    StatusText = txt + luaitem.Name;
                    luaitem.CallPlot_Check();
                    item = luaitem.lviTag;
                    item.ImageIndex = luaitem.ImageIndex;
                    if (luaitem.RelatedFile != null)
                    {
                        item.ImageKey = luaitem.RelatedFile;
                    }

                    listView_Item.Items.Add(item);
                    ProgressBarValue++;
                }
                ProgressBarVisible = false;
                StatusText = lang.GetString("Ready");
            }

            listView_Item.AutoResizeColumns(ColumnHeaderAutoResizeStyle.HeaderSize);
            LuaListView.NowNode = newSelected;
            InitDirLabel(newSelected.FullPath);
            GC.Collect();
        }

        /// <summary>
        /// rename
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void listView_Item_AfterLabelEdit(object sender, LabelEditEventArgs e)
        {
            if (e.Label == null) return;
            LuaItem lp = (LuaItem)this.listView_Item.FocusedItem.Tag;
            if (lp.Text == "..") { e.CancelEdit = true; return; }
            
            string NewLabel = e.Label.Trim();
            lp.Text = NewLabel;
            if (lp.Text != NewLabel) e.CancelEdit = true;
            lp.SaveSetting();
        }


        private void AddNewItem(string FilePath)
        {
            if (!File.Exists(FilePath)) return;
            
            string TargetFilePath = FilePath;
            string ext = Path.GetExtension(TargetFilePath).ToLower();
            LuaItem luaitem = (LuaItem)LuaListView.NowNode.Tag;
            string LuaPath = luaitem.dir.FullName;
            string OrgName = Path.GetFileNameWithoutExtension(TargetFilePath);
            string name = OrgName;
            string MD = Path.Combine(LuaPath, OrgName);
            int counter = 1;
            while (Directory.Exists(MD))
            {
                MD = Path.Combine(LuaPath, OrgName + "_" + counter++);
            }

            if (ext == ".7z")
            {

                if (Archiver.C7Z.ExtractingFile(FilePath, MD))
                {
                    DirectoryInfo _di = new DirectoryInfo(MD);
                    LuaItem _newluaitem = LuaListView.CreateLuaItem(_di, luaitem, true);
                    LuaListView.AddImageList(_newluaitem);
                    luaitem.sublp.Add(_newluaitem);
                    EnterList(LuaListView.NowNode);
                }
                return;
            }
            //create shortcut
           
            string WorkingDirectory = Path.GetDirectoryName(TargetFilePath);
            string Arguments = "";
            string apploc_arg = "";
            IconLocation IconPath = new IconLocation(FilePath, 0);
            while (ext == ".lnk")
            {
                ShellLink shortcut = new ShellLink(TargetFilePath);
                TargetFilePath = shortcut.TargetPath;
                name = Path.GetFileNameWithoutExtension(TargetFilePath);
                ext = Path.GetExtension(TargetFilePath);
                WorkingDirectory = shortcut.WorkingDirectory;
                Arguments = shortcut.Arguments;
                IconPath = shortcut.IconLocation;
                if (IconPath.File == "") IconPath.File = TargetFilePath;
                if (name.ToLower() == "apploc")
                {
                    List<string> arg = GetArguments(Arguments);
                    if (arg.Count > 0)
                    {
                        if (File.Exists(arg[0]))
                        {
                            TargetFilePath = arg[0];
                            name = Path.GetFileNameWithoutExtension(TargetFilePath);
                            ext = Path.GetExtension(TargetFilePath);
                            Arguments = "";
                            for (int i = 1; i < arg.Count; i++)
                            {
                                string a = arg[i].Trim();
                                if (a.Length == 6 && a.Substring(0, 2) == "/L")
                                {
                                    apploc_arg = a;
                                }
                                else
                                {
                                    Arguments += "\"" + arg[i] + "\" ";
                                }
                            }
                            Arguments = Arguments.Trim();
                            if (WorkingDirectory.Trim() == "") WorkingDirectory = Path.GetDirectoryName(TargetFilePath);
                        }
                    }
                }
            }

            DirectoryInfo di = Directory.CreateDirectory(MD);
            if (!di.Exists)
            {
                MessageBox.Show(lang.GetString("Can not create file."), lang.GetString("Error"), MessageBoxButtons.OKCancel, MessageBoxIcon.Error);
                return;
            }

            //Create Lua file
            File.Copy(Path.Combine(LuaSystemPath, "NewFileTemplet.lua_"), Path.Combine(MD, name + ".lua"));

            //create setting.lua
            StreamWriter sw = new StreamWriter(Path.Combine(MD, "setting.lua"), false, Encoding.Unicode);
            sw.Write(string.Format("setting.Title = \"{0}\"\r\n", OrgName));
            sw.Write(string.Format("setting.FilePath = \"{0}\"\r\n", Common.GetRelativePath(MainPath, TargetFilePath).Replace(@"\", @"\\").Replace("\"", "\\\"")));
            if (File.Exists(WorkingDirectory) && WorkingDirectory != "")
                sw.Write(string.Format("setting.WorkingDirectory = \"{0}\"\r\n", Common.GetRelativePath(WorkingDirectory, TargetFilePath).Replace(@"\", @"\\").Replace("\"", "\\\"")));
            else
                sw.Write("setting.WorkingDirectory = \"\"\r\n");

            sw.Write(string.Format("setting.Arguments = \"{0}\"\r\n", Arguments.Replace(@"\", @"\\").Replace("\"", "\\\"")));
            sw.Write(string.Format("setting.IconPath = \"{0}\"\r\n", IconPath.File.Replace(@"\", @"\\").Replace("\"", "\\\"")));
            sw.Write(string.Format("setting.IconIndex = {0}\r\n", IconPath.Index));
            sw.Close();

            //create language.ini
            string EncName = Encoding.Default.WebName;
            sw = new StreamWriter(Path.Combine(MD, EncName + ".ini"), false, Encoding.Unicode);
            sw.Write(string.Format("[{0}]\n{1}={1}\n", EncName, name));
            sw.Close();

            LuaItem newluaitem = LuaListView.CreateLuaItem(di, luaitem, true);
            if (apploc_arg != "")
            {
                newluaitem.AppLocSetup(apploc_arg);
                newluaitem.apploc.key = apploc_arg;
                newluaitem.apploc.Enable = true;
            }
            LuaListView.AddImageList(newluaitem);
            luaitem.sublp.Add(newluaitem);
            EnterList(LuaListView.NowNode);

        }

        private List<string> GetArguments(string Arguments)
        {
            List<string> arg = new List<string>();
            Arguments = Arguments.Trim();
            int LI = -1; int RI = -1; int start = 0;
            while (start < Arguments.Length)
            {
                if (Arguments.Substring(start, 1) == "\"")
                {
                    LI = start;
                    RI = Arguments.IndexOf('"', LI + 1);
                    if (RI > -1)
                    {
                        string value = Arguments.Substring(LI + 1, RI - LI - 1);
                        if (value.Trim() != "") arg.Add(value);
                        start = RI + 1;
                    }
                    else
                        return arg;
                }
                else
                {
                    LI = start-1;
                    RI = Arguments.IndexOf(' ', LI + 1);
                    if (RI > -1)
                    {
                        string value = Arguments.Substring(LI + 1, RI - LI - 1);
                        if (value.Trim() != "") arg.Add(value);
                        start = RI + 1;
                    }
                    else
                        return arg;
                }
            }
            return arg;
        }

        #region DragDrop

        private void listView_Item_DragEnter(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
                e.Effect = DragDropEffects.All;
            else
                e.Effect = DragDropEffects.None;

        }

        private void listView_Item_DragDrop(object sender, DragEventArgs e)
        {
            string[] s = (string[])e.Data.GetData(DataFormats.FileDrop, false);
            int i = 0;
            ProgressBarMax = s.Length; ProgressBarMin = 0; ProgressBarValue = 0; ProgressBarVisible = true;
            for (i = 0; i < s.Length; i++)
            {
                AddNewItem(s[i]);
                ProgressBarValue = i;
            }
            ProgressBarVisible = false;
        }
        private void textBox_CheckFile_DragEnter(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
                e.Effect = DragDropEffects.All;
            else
                e.Effect = DragDropEffects.None;

        }

        private void textBox_CheckFile_DragDrop(object sender, DragEventArgs e)
        {
            string[] s = (string[])e.Data.GetData(DataFormats.FileDrop, false);
            int i;
            for (i = 0; i < s.Length; i++)
            {
                string ext = Path.GetExtension(s[i]).ToLower();
                if (File.Exists(s[i]) && ext != ".lnk")
                {
                    CRC_File cf = new CRC_File(s[i]);
                    string filename = Path.GetFileName(s[i]);

                    string CheckData = string.Format("[{0}] crc = {1} hex = {2}{3}", filename, cf.CRC32CheckSum, cf.CRC32CheckSumHex, Environment.NewLine);


                    this.textBox_CheckFile.Text = CheckData;
                    if (ext == ".exe" || ext == ".dll")
                    {
                        FileVersionInfo fvi = FileVersionInfo.GetVersionInfo(s[i]);
                        CheckData += string.Format("Version = {0}{1}", fvi.ProductVersion.ToString(), Environment.NewLine);

                        this.textBox_CheckFile.Text = CheckData;
                    }
                }
            }

        }

        #endregion

        #region ToolStripMenuItem
        private void toolStripTextBox_Arg_TextChanged(object sender, EventArgs e)
        {
            LuaItem lp = (LuaItem)this.listView_Item.FocusedItem.Tag;
            if (lp.Arguments != toolStripTextBox_Arg.Text)
            {
                lp.Arguments = toolStripTextBox_Arg.Text;
            }
        }

        private void runToolStripMenuItem_Click(object sender, EventArgs e)
        {
            listView_Item_ItemActivate(sender, e);
        }

        private void copyToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.richTextBox_Log.Copy();
        }

        private void clearToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.richTextBox_Log.Clear();
        }

        private void deleteToolStripMenuItem_Click_1(object sender, EventArgs e)
        {
            if (this.listView_Item.SelectedItems.Count == 0) return;
            DialogResult dr = MessageBox.Show(lang.GetString("Are you sure you want to delete this item?"), lang.GetString("Warning"), MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
            if (dr == DialogResult.Yes)
            {
                LuaItem lp = (LuaItem)this.listView_Item.FocusedItem.Tag;
                if (lp.delete())
                {
                    lp.Remove();
                    EnterList(LuaListView.NowNode);
                }
            }
        }
        private void newFolderToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            LuaItem luaitem = (LuaItem)LuaListView.NowNode.Tag;
            string LuaPath = luaitem.dir.FullName;
            DirectoryInfo di = new DirectoryInfo(LuaPath);
            FileInfo[] files = di.GetFiles("*.*");
            DirectoryInfo[] dirs = di.GetDirectories("*.*");
            string NewFolderBase = "New Folder ";
            int index = 1;
            string NewFolder = "";
            while (true)
            {
                NewFolder = NewFolderBase + index.ToString();
                bool find = false;
                foreach (FileInfo fi in files)
                {
                    if (fi.Name == NewFolder) { find = true; break; }
                }
                foreach (DirectoryInfo d in dirs)
                {
                    if (d.Name == NewFolder) { find = true; break; }
                }
                if (find)
                    index++;
                else
                    break;
            }
            string MD = Path.Combine(LuaPath, NewFolder);
            if (Directory.Exists(MD))
            {
                MessageBox.Show(lang.GetString("Directory already exists."), lang.GetString("Error"), MessageBoxButtons.OKCancel, MessageBoxIcon.Error);
                return;
            }
            if (MD.Length>248)
            {
                MessageBox.Show(lang.GetString("Can not create file.") + " Path is too long.", lang.GetString("Error"), MessageBoxButtons.OKCancel, MessageBoxIcon.Error);
                return;
            }
            Directory.CreateDirectory(MD);
            di = new DirectoryInfo(MD);
            if (!di.Exists)
            {
                MessageBox.Show(lang.GetString("Can not create file."), lang.GetString("Error"), MessageBoxButtons.OKCancel, MessageBoxIcon.Error);
                return;
            }

            LuaItem newluaitem = LuaListView.CreateLuaItem(di, luaitem,null);
            newluaitem.UpTreeNode = luaitem.tn;
            newluaitem.ImageIndex = 1;
            TreeNode aNode = new TreeNode(di.Name);
            aNode.Tag = newluaitem;
            newluaitem.tn = aNode;
            newluaitem.sublp = new List<LuaItem>();
            luaitem.sublp.Add(newluaitem);

            LuaItem luaitemUpTree = new LuaItem("..", di, newluaitem, null, true);
            luaitemUpTree.UpTreeNode = LuaListView.NowNode;
            luaitemUpTree.ImageIndex = 0;
            newluaitem.sublp.Add(luaitemUpTree);
            LuaListView.NowNode.Nodes.Add(aNode);
            EnterList(LuaListView.NowNode);

        }

        private void newFormToolStripMenuItem_Click(object sender, EventArgs e)
        {
            LuaItem luaitem = (LuaItem)LuaListView.NowNode.Tag;
            string LuaPath = luaitem.dir.FullName;
            DirectoryInfo di = new DirectoryInfo(LuaPath);
            FileInfo[] files = di.GetFiles("*.*");
            DirectoryInfo[] dirs = di.GetDirectories("*.*");
            string NewFolderBase = "New form ";
            int index = 1;
            string NewFolder = "";
            while (true)
            {
                NewFolder = NewFolderBase + index.ToString();
                bool find = false;
                foreach (FileInfo fi in files)
                {
                    if (fi.Name == NewFolder) { find = true; break; }
                }
                foreach (DirectoryInfo d in dirs)
                {
                    if (d.Name == NewFolder) { find = true; break; }
                }
                if (find)
                    index++;
                else
                    break;
            }
            string MD = Path.Combine(LuaPath, NewFolder);
            if (Directory.Exists(MD))
            {
                MessageBox.Show(lang.GetString("Directory already exists."), lang.GetString("Error"), MessageBoxButtons.OKCancel, MessageBoxIcon.Error);
                return;
            }
            Directory.CreateDirectory(MD);
            di = new DirectoryInfo(MD);
            if (!di.Exists)
            {
                MessageBox.Show(lang.GetString("Can not create file."), lang.GetString("Error"), MessageBoxButtons.OKCancel, MessageBoxIcon.Error);
                return;
            }

            //Create Lua file
            File.Copy(Path.Combine(LuaSystemPath, "FormTemplet.lua_"), Path.Combine(MD, "FormTemplet.lua"));
            File.Copy(Path.Combine(LuaSystemPath, "NewTemplet.lua_"), Path.Combine(MD, "NewTemplet.lua"));

            //create setting.lua
            StreamWriter sw = new StreamWriter(Path.Combine(MD, "setting.lua"), false, Encoding.Unicode);
            sw.Write(string.Format("setting.Title = \"{0}\"\r\n", NewFolder));
            sw.Close();

            //create language.ini
            string EncName = Encoding.Default.WebName;
            sw = new StreamWriter(Path.Combine(MD, EncName + ".ini"), false, Encoding.Unicode);
            sw.Write(string.Format("[{0}]\n{1}={1}\n", EncName, NewFolder));
            sw.Close();

            LuaItem newluaitem = LuaListView.CreateLuaItem(di, luaitem, false);
            //LuaListView.AddImageList(newluaitem);
            luaitem.sublp.Add(newluaitem);
            EnterList(LuaListView.NowNode);

        }
        private void exportTo7zipToolStripMenuItem_Click(object sender, EventArgs e)
        {
            LuaItem lp = (LuaItem)this.listView_Item.FocusedItem.Tag;
            string LuaPath = lp.dir.FullName;
            string luaName = Path.GetFileName(lp.dir.FullName);

            if (saveFileDialog1.InitialDirectory.ToUpper().IndexOf(LuaPath.ToUpper()) >= 0)
                saveFileDialog1.InitialDirectory = "";

            if (saveFileDialog1.InitialDirectory == "")
                saveFileDialog1.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

            this.saveFileDialog1.Title = lang.GetString("Compression") + lp.Name;
            this.saveFileDialog1.FileName = luaName + ".7z";

            if (this.saveFileDialog1.ShowDialog() == DialogResult.Cancel) return;
            if (saveFileDialog1.InitialDirectory.ToUpper().IndexOf(LuaPath.ToUpper()) >= 0) return;

            StatusText =  lang.GetString("Please wait...");
            //bool ret = Archiver.C7Z.Compress7Z(LuaPath, this.saveFileDialog1.FileName);
            ProgressForm pf = new ProgressForm(LuaPath, this.saveFileDialog1.FileName);
            DialogResult dr = pf.ShowDialog();

            StatusText = lang.GetString("Ready");
            //if (!ret)
            //    MessageBox.Show(lang.GetString("Can not create file."), lang.GetString("Error"), MessageBoxButtons.OKCancel, MessageBoxIcon.Error);
        }

        #endregion

        private void listView_Item_MouseMove(object sender, MouseEventArgs e)
        {
            ListViewItem lv = listView_Item.GetItemAt(e.X, e.Y);

            if (lv != null)
            {
                if (toolTip.Tag == (object)lv) return;

                LuaItem lp = (LuaItem)lv.Tag;
                if (lp.HaveInfo)
                {
                    string[] text = lp.GetInfo();
                    string[] lines = text[0].Split(new char[] { '\n' });
                    int maxLength = lv.Text.Length;
                    foreach (string t in lines)
                    {
                        if (t.Length > maxLength && t.Length < 60)
                            maxLength = t.Length;
                    }
                    string Title = lv.Text;
                    if (maxLength != Title.Length)
                    {
                        for (int i = lv.Text.Length; i < maxLength; i++)
                        {
                            Title += " ";
                        }
                    }
                    toolTip.ToolTipTitle = Title;
                    toolTip.Tag = lv;
                    toolTip.SetToolTip(listView_Item, text[0]);
                    toolTip.OwnerDraw = true;
                    
                }
            }
            else
            {
                toolTip.SetToolTip(listView_Item, "");
                toolTip.Tag = null;
            }
        }

        #region AppLoc
        private void AppLocMenu(LuaItem lp)
        {
            if (lp.NoApploc || lp.sublp != null || lp.UpTreeNode != null || !lp.CanRun || lp.RelatedFile == null || !File.Exists(lp.RelatedFile)) //is group
            {
                this.toolStripSeparator2.Visible = false;
                codePageToolStripMenuItem.Visible = false;
                return;
            }

            this.toolStripSeparator2.Visible = true;
            codePageToolStripMenuItem.Visible = true;
            
            traditionalChineseToolStripMenuItem.Checked = false;
            japaneseToolStripMenuItem.Checked = false;
            koreanToolStripMenuItem.Checked = false;
            simplifiedChineseToolStripMenuItem.Checked = false;
            codePageToolStripMenuItem.Checked = false;
            if (lp.apploc.Enable)
            {
                switch (lp.apploc.key)
                {
                    case ("/L0804"):
                        simplifiedChineseToolStripMenuItem.Checked = true;
                        codePageToolStripMenuItem.Checked = true;
                        break;
                    case ("/L0412"):
                        koreanToolStripMenuItem.Checked = true;
                        codePageToolStripMenuItem.Checked = true;
                        break;
                    case ("/L0411"):
                        japaneseToolStripMenuItem.Checked = true;
                        codePageToolStripMenuItem.Checked = true;
                        break;
                    case ("/L0404"):
                        traditionalChineseToolStripMenuItem.Checked = true;
                        codePageToolStripMenuItem.Checked = true;
                        break;
                }
            }
        }
        private void AppLocCheck(object sender, EventArgs e)
        {
            ToolStripMenuItem tsmi = (ToolStripMenuItem)sender;
            LuaItem lp = (LuaItem)this.listView_Item.FocusedItem.Tag;
            if (lp.sublp != null || lp.UpTreeNode != null) //is group
            {
                return;
            }

            bool SwitchChecked = !tsmi.Checked;

            traditionalChineseToolStripMenuItem.Checked = false;
            japaneseToolStripMenuItem.Checked = false;
            koreanToolStripMenuItem.Checked = false;
            simplifiedChineseToolStripMenuItem.Checked = false;

            tsmi.Checked = SwitchChecked;
            codePageToolStripMenuItem.Checked = tsmi.Checked;

            
            lp.apploc.Enable = tsmi.Checked;
            if (tsmi.Checked)
            {
                lp.apploc.Setup((string)tsmi.Tag);
            }
            else
                lp.apploc.Setup("");
        }
        #endregion

        private void richTextBox_Log_LinkClicked(object sender, LinkClickedEventArgs e)
        {
            ProcessStartInfo sInfo = new ProcessStartInfo(e.LinkText);
            Process.Start(sInfo);
        }

        private void textBox_Title_TextChanged(object sender, EventArgs e)
        {
            Common.SetTitle(textBox_Title.Text);
            if (Common.LuaBoardTitle != "")
                this.Text = string.Format("{0} - LuaBoard {1}", lang.GetString(Common.LuaBoardTitle), base.ProductVersion);
            else
                this.Text = string.Format("LuaBoard {0}", base.ProductVersion);

        }

        private void buttonAbout_Click(object sender, EventArgs e)
        {
            AboutBox form = new AboutBox();
            form.ShowDialog();
        }

        private void comboBox_Option_CmpLevel_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (!Ready) return;
            Common.SetCompressionLevel(comboBox_Option_CmpLevel.SelectedIndex);
        }

        private void checkBox_ShowDebug_CheckedChanged(object sender, EventArgs e)
        {
            Common.SetShowDebugMessage(checkBox_ShowDebug.Checked);

        }




    }


    
}
